package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /*添加购物车*/
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
        //获取当前登入者
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);
        //获取登入者后，要把当前购物选项返回
        shoppingCart = shoppingCartService.add(shoppingCart);
        return R.success(shoppingCart);
    }

    /*查询购物车*/
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpSession session) {
        //获取当前登入者
        Long userId = (Long) session.getAttribute("user");
        //根据当前登入者查看购物车
        List<ShoppingCart> shoppingCartList = shoppingCartService.findCartByUserId(userId);
        return R.success(shoppingCartList);
    }
    /*清除购物车*/
    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){
        //获取当前登入者信息
        Long userId = (Long) session.getAttribute("user");
        //根据用户清空购物车
        shoppingCartService.clean(userId);
        return R.success("清除成功");
    }
    /*删除购物车商品*/
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart,HttpSession session){
        //获取当前登入者
       Long userId = (Long) session.getAttribute("user");

       //把当前购物选项返回
        shoppingCartService.sub(shoppingCart,userId);
        return R.success("删除成功");
    }

}
